package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.config.R;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 前台登录
 */
@RestController
@RequestMapping("/home")
@Slf4j
public class YddLoginController {

   @Autowired
   private IYddUserService yddUserService;

   @PostMapping("/index/login")
    public R<HashMap> login(@RequestBody Map map){
       //接收页面请求的参数
       String mobile = map.get("mobile").toString();
       String password = DigestUtils.md5DigestAsHex(map.get("password").toString().getBytes());
       //查询数据库是否存在相同手机号的用户
       LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(YddUser::getMobile,mobile);
       YddUser yddUser = yddUserService.getOne(queryWrapper);

       HashMap<String, Object> ret = new HashMap<>();

       //判断穿过来的用户是否存在,密码是否正确
       if (yddUser!=null&&yddUser.getPassword().equals(password)){
           //登录成功 ,生成token传回页面
           HashMap< String, Object> tokenMap = new HashMap<>();
           tokenMap.put("id",yddUser.getId());
           String token = JwtUtils.getToken(tokenMap);
           ret.put("token",token);

           return R.success(ret);
       }else {
           return R.error("登录失败");
       }

   }
}
